sub win2dos;

if( $#ARGV >= 0 )
{
    $StartAt = $ARGV[0];
}
else
{
    $StartAt = 1;
}

$Count = 0;
$Digits = length($StartAt);
$StartAt++;
$StartAt--;

opendir(DIR, ".") || die "Can't opendir .: $!";
while($file = readdir(DIR))
{
  if( $file =~ /\.mp3$/i )
  {
    $Count ++;
    if( ($file =~ /^(\d\d)/) and ($Digits < 2) )
    {
      $Digits = 2;
    }
    if( $file =~ /^(\d\d\d)/ )
    {
      $Digits = 3;
    }
  }
}
closedir DIR;

if( ($StartAt - 1 + $Count > 9) and ($Digits == 1) )
{
  $Digits = 2;
}
if( ($StartAt - 1 + $Count > 99) and ($Digits == 2) )
{
  $Digits = 3;
}

$i = $StartAt;
opendir(DIR, ".");
while($file = readdir(DIR))
{
  if( $file =~ /\.mp3$/i )
  {
    $file2 = $file;
    $file2 =~ s/^\d\d?\d?//;
    if( (substr($file2, 0, 1) eq ".") or
        (substr($file2, 0, 1) eq " ") )
    {
      $file2 = "$i$file2";
    }
    else
    {
      $file2 = "$i $file2";
    }
    if   ( $i < 10  )  { $d = 1; }
    elsif( $i < 100 )  { $d = 2; }
    else               { $d = 3; }

    if( $Digits > $d   ) { $file2 = "0".$file2; }
    if( $Digits > $d+1 ) { $file2 = "0".$file2; }

    $hash{$file} = $file2;
    $i ++;
  }
}
closedir DIR;

$prefx="un0Urf45Mg2fz";

foreach $k ( keys %hash )
{
  rename($k, $prefx.$hash{$k});
  #print win2dos("$k -> ".$hash{$k}."\n");
}

foreach $k ( keys %hash )
{
  rename($prefx.$hash{$k}, $hash{$k});
  #print win2dos("$k -> ".$hash{$k}."\n");
}

sub win2dos
{
  my $sSrc = $_[0];
  my $sDst = "";
  my $iSrcLen = length($sSrc);
  my $i;
  for( $i = 0; $i < $iSrcLen; $i ++ )
  {
    $c = ord(substr($sSrc, $i, 1));
    if(   ($c >= 192) and ($c <= 223) )    { $c += (128-192); }
    elsif( $c == 184)                      { $c =   241; }
    elsif( $c == 168 )                     { $c =   240; }
    elsif(($c >= 224) and ($c <= 239) )    { $c += (160-224); }
    elsif(($c >= 240) and ($c <= 255) )    { $c += (224-240); }
    $sDst .= chr($c);
  }
  return $sDst;
} #win2dos
